package com.atguigu.day07;

import com.atguigu.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;

public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("/home/zuoyuan/flinktutorial0212/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String in) throws Exception {
                        String[] array = in.split(",");
                        return new UserBehavior(
                                array[0], array[1], array[2], array[3],
                                Long.parseLong(array[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                )
                .keyBy(r -> 1)
                .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(5)))
                .process(new ProcessWindowFunction<UserBehavior, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer key, Context ctx, Iterable<UserBehavior> elements, Collector<String> out) throws Exception {
                        // key: productId
                        // value: 浏览次数
                        HashMap<String, Long> hashMap = new HashMap<>();

                        for (UserBehavior e : elements) {
                            if (!hashMap.containsKey(e.productId)) {
                                hashMap.put(e.productId, 1L);
                            } else {
                                hashMap.put(e.productId, hashMap.get(e.productId) + 1L);
                            }
                        }

                        ArrayList<Tuple2<String, Long>> arrayList = new ArrayList<>();
                        for (String k : hashMap.keySet()) {
                            arrayList.add(Tuple2.of(k, hashMap.get(k)));
                        }

                        arrayList.sort(new Comparator<Tuple2<String, Long>>() {
                            @Override
                            public int compare(Tuple2<String, Long> t1, Tuple2<String, Long> t2) {
                                return (int)(t2.f1 - t1.f1);
                            }
                        });

                        StringBuilder result = new StringBuilder();
                        result.append("==========================================\n");
                        result.append(new Timestamp(ctx.window().getStart()) + "~" + new Timestamp(ctx.window().getEnd()) + "\n");
                        for (int i = 0; i < 3; i++) {
                            Tuple2<String, Long> tmp = arrayList.get(i);
                            result.append("第" + (i+1) + "名的商品ID：" + tmp.f0 + "，浏览次数：" +
                                    "" + tmp.f1 + "\n");
                        }
                        result.append("==========================================\n");
                        out.collect(result.toString());
                    }
                })
                .print();

        env.execute();
    }
}
